package com.oa.dao.impl;

import com.oa.common.enums.apps.DbType;
import com.oa.common.enums.apps.FromFileType;
import com.oa.common.eums.EntityStatus;
import com.oa.common.interfaces.PreFilter;
import com.oa.dao.BaseDaoImpl;
import com.oa.dao.FormDao;
import com.oa.dao.PreFilters;
import com.oa.entities.flows.Form;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class FormDaoImpl extends BaseDaoImpl<Long,Form> implements FormDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    protected void loadClassType() {
        setType(Form.class);
    }

    @Override
    public void alterTable(Form form) {
        Long typeId= form.getTypeId();
        StringBuilder builder= new StringBuilder();
        if (form.getDbType()==DbType.INTEGER.getCode()){
            builder.append("alter table oa_apps_"+typeId+" add "+ form.getInputName()+" int(11) null;");
        }else if (form.getFileType()==FromFileType.TEXTAREA.getCode()){
            builder.append("alter table oa_apps_"+typeId+" add "+ form.getInputName()+" TEXT NULL;");
        }else {
            builder.append("alter table oa_apps_"+typeId+" add "+form.getInputName()+" varchar(255) null;");
        }
        jdbcTemplate.execute(builder.toString());
    }

    @Override
    public List<Form> findForm(Long typeId) {
        List<PreFilter> filters=new ArrayList<>();
        filters.add(PreFilters.eq(Form.PROP_STATUS,EntityStatus.ENTITY_EABLE.getCode()));
        filters.add(PreFilters.eq(Form.FORM_TYPE_ID,typeId));
        PreFilter[] fs= new PreFilter[filters.size()];
        return findByPrefilter(filters.toArray(fs));
    }

    @Override
    public Form find(Long typeId, String name) {
        List<PreFilter> filters= new ArrayList<>();
        filters.add(PreFilters.eq(Form.PROP_STATUS,EntityStatus.ENTITY_EABLE.getCode()));
        filters.add(PreFilters.eq(Form.FORM_TYPE_ID,typeId));
        filters.add(PreFilters.eq(Form.FORM_INPUT_NAME,name));
        PreFilter[] fs= new PreFilter[filters.size()];
        return findUnqiue(filters.toArray(fs));
    }
}
